package cn.takovh.zpl;

import cn.takovh.zpl.bean.Media;
import cn.takovh.zpl.bean.Smil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.tree.DefaultProcessingInstruction;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Zoom Player List
 */
public class ZPL {
    private static final String version = "2.0";

    private Smil smil;

    public ZPL(Smil smil) {
        this.smil = smil;
    }

    public ZPL(String title, List<Media> mediaList) {
        this.smil = new Smil(title, mediaList);
    }

    public String getVersion() {
        return version;
    }

    public Smil getSmil() {
        return smil;
    }

    public void setSmil(Smil smil) {
        this.smil = smil;
    }

    public Document getDocument() {
        Map<String, String> map = new HashMap<>();
        map.put("version", version);
        // 创建document对象
        Document document = DocumentHelper.createDocument();
        document.addProcessingInstruction("zpl", map);
        // 创建根节点
        Element root = document.addElement("smil");
        smil.getElement(root);
        return document;
    }

    public static ZPL parse(Document document) throws DocumentException {
        List<Node> nodeList = document.content();
        DefaultProcessingInstruction instruction = (DefaultProcessingInstruction) nodeList.get(0);
        String ver = instruction.getValue("version");
        if (!ver.equals(version)) throw new DocumentException("仅支持版本2.0");
        Element element = document.getRootElement();
        Smil smil = new Smil();
        smil.parseElement(element);
        return new ZPL(smil);
    }
}
